import os, sys
APPLICATION_INSTALL_DIR = os.environ.get('SIMPLEAUTH_INSTALL')
if not APPLICATION_INSTALL_DIR:
    raise EnvironmentError("Must Set SIMPLEAUTH_INSTALL in the environment!")

sys.path.append(os.path.join(APPLICATION_INSTALL_DIR, "lib%spython" % os.sep))

from sqlalchemy import *
from simple_auth import model as sa_model

def authenticate(username, password, resource_name, session=None):
    localSession = False
    if session is None:
        session = create_session()
        localSession = True
    response = None

    resource = session.query(sa_model.Resource).get_by(name=resource_name)
    if resource:
        user = session.query(sa_model.ResourceUser).selectfirst(and_(
            sa_model.ResourceUser.c.resource_id==resource.id,
            sa_model.ResourceUser.c.name==username))
        if user:
            if user.password == password:
                response = True
            else:
                response = False
        else:
            response = False
    else:
        response = False
    if localSession:
        session.close()
    return response


def authorize(servicename, username, rolename, resource_name, session=None):
    localSession = False
    if session is None:
        session = create_session()
        localSession = True
    response = None
    resource = session.query(sa_model.Resource).get_by(name=resource_name)
    user = None
    if resource:
        user = session.query(sa_model.ResourceUser).selectfirst(and_(
            sa_model.ResourceUser.c.resource_id==resource.id,
            sa_model.ResourceUser.c.name==username))
    service = session.query(sa_model.Service).get_by(name=servicename)
    role = session.query(sa_model.Role).get_by(name=rolename)
    if user and service and role:
        if role in user.roles and role in service.roles:
            response = True
        else:
            response = False
    else:
        response = False
    if localSession:
        session.close()
    return response
    

def get_roles_for_user(servicename, username, resource_name, session=None):
    localSession = False
    if session is None:
        session = create_session()
        localSession = True
    response = []
    resource = session.query(sa_model.Resource).get_by(name=resource_name)
    user = None
    if resource:
        user = session.query(sa_model.ResourceUser).selectfirst(and_(
            sa_model.ResourceUser.c.resource_id==resource.id,
            sa_model.ResourceUser.c.name==username))
    service = session.query(sa_model.Service).get_by(name=servicename)

    if service and user:
        for role in service.roles:
            if role in user.roles:
                response.append(role.name)
    
    if localSession:
        session.close()
    return response